package com.superlistaportable.productList;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import com.superlistaportable.resultList.ResultListActivity;
import com.superlistaportable.sales.SalesActivity;

public class ProductListController {

	private final ProductListView view;
	private final ProductListModel model;
	private final ProductListActivity activity;
	private String selectedSupermarket;
	private ProductListController controller = this;
	private boolean updating = false;
	
	public ProductListController(ProductListModel model, ProductListView view, ProductListActivity activity, Intent i) {
		this.view = view;
		this.model = model;
		this.activity = activity;
		Bundle extras = i.getExtras();
		if (extras != null) {
			selectedSupermarket = extras.getString("selectedSupermarket");
        }
		loadList();
	}
	
	private void loadList() {
		//Cargamos la lista con lo que habiamos consultado la ultima vez,por default
		FileInputStream fis;
		try {
			fis = activity.getApplicationContext().openFileInput(selectedSupermarket+	".xml");
		StringBuffer fileContent = new StringBuffer("");

		byte[] buffer = new byte[40000];

		while (fis.read(buffer) != -1) {
		    fileContent.append(new String(buffer));
		}
		model.buildSavedListAndItemCost(fileContent.toString());
		view.buildExpandableList();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	public void setListeners() {
		
		view.getButtonNext().setOnClickListener(new OnClickListener() {
			//Pasa los items con stock a la siguiente actividad, para generar la lista final
			@Override
			public void onClick(View v) {
		    	Intent intent = new Intent(activity, ResultListActivity.class);
		    	intent.putStringArrayListExtra("itemsWithStock",(ArrayList<String>) model.getItemsWithStock());
		    	intent.putExtra("totals", model.getTotals());
		    	activity.startActivity(intent);
			}
		});
		
		view.getButtonSales().setOnClickListener(new OnClickListener() {
			//Ver ofertas para el supermercado seleccionado, inicia la activity de sales
			@SuppressLint("NewApi")
			@Override
			public void onClick(View v) {
		        if (android.os.Build.VERSION.SDK_INT > 9) {
		            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		            StrictMode.setThreadPolicy(policy);
		        }
				Intent intent = new Intent(activity, SalesActivity.class);
				intent.putExtra("selectedSupermarket", selectedSupermarket);
				activity.startActivity(intent);
			}
		});
		
		view.getButtonReload().setOnClickListener(new OnClickListener() {
			//Actualizar la lista de productos con un llamado al server
			@Override
			public void onClick(View v) {
				if (preExecAsyncTask()) {
					Toast.makeText(activity.getApplicationContext(), "Actualizando...",Toast.LENGTH_SHORT).show();
					ProductListAsyncTask task = new ProductListAsyncTask();
			        task.execute(controller);
				}
			}
		});
	}
	synchronized public boolean preExecAsyncTask() {

		if (updating) return false;
		
		// Disable update, para que no realicen multiples llamados
		disableUpdate();
		updating = true;
		return updating;
	}
	public synchronized void postExecAsyncTask(String result) {
		//En base a la respuesta, arrojo un toast de error o construyo la lista y muestro un toast de act completa
		if (updating) {
			if(!result.equals("Error al acceder al server")){
				view.buildExpandableList();
				saveResponseXML(result);
				Toast.makeText(activity.getApplicationContext(), "Actualizacion Completa",Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(activity.getApplicationContext(), "Fallo la conexión",Toast.LENGTH_SHORT).show();
			}
			enableUpdate();
			updating = false;
		}
	}
		
	private void saveResponseXML(String result) {
		//guardamos la respuesta obtenida para no tener que consultar al servidor 
		//cada vez que se reinicie la activity
		FileOutputStream outputStream;

		try {	
			  outputStream = activity.getApplicationContext().openFileOutput(selectedSupermarket+".xml", activity.getApplicationContext().MODE_PRIVATE);
			  outputStream.write(result.getBytes());
			  outputStream.close();
			} catch (Exception e) {
			  e.printStackTrace();
			}
	}

	
	public void disableUpdate() {
		// Disable button
		getView().enableUpdatebutton(false);	
	}
	
	public void enableUpdate() {
		// Disable button
		getView().enableUpdatebutton(true);	
	}
	
	public ProductListModel getModel(){
		return model;
	}
	public ProductListView getView(){
		return view;
	}
	public String getSelectedSupermarket(){
		return selectedSupermarket;
	}
}
